package vip.xiaonuo.digest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.joe.util.GsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import vip.xiaonuo.megvii.BaseConfig;
import vip.xiaonuo.megvii.config.model.ApiResponse;
import vip.xiaonuo.megvii.facegroups.model.FaceGroup;

import java.io.IOException;
import java.nio.charset.Charset;

@Slf4j
public class DigestHttpUtil {

    private DigestHttpUtil(){}

    public synchronized static ApiResponse sendGet(HttpClient client,String url ){
        HttpGet httpGet = new HttpGet(url);
        HttpEntity entity = null;
        try {
            //queryBusyStats(client,url);

            HttpResponse resp = client.execute(httpGet);
            int statusCode = resp.getStatusLine().getStatusCode();

            try{
                entity = resp.getEntity();
                String json = EntityUtils.toString(entity);
                log.info("{} 请求返回结果：{}",url,json);
                return JSON.parseObject(json, ApiResponse.class);
            }catch (Exception e) {
                return ApiResponse.failed(statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ApiResponse.failed(500,"连接失败，请检查设备的网络参数!!!");
        }
    }

    public synchronized static ApiResponse sendPost(HttpClient client ,String url, String param) {
        HttpPost httpPost = new HttpPost(url); //建立HttpPost对象
        HttpEntity entity = null;
        try {
            //queryBusyStats(client,url);

            StringEntity stringEntity = new StringEntity(param,Charset.forName("UTF-8"));
            httpPost.setEntity(stringEntity);
            //添加参数
            HttpResponse resp = client.execute(httpPost);
            int statusCode = resp.getStatusLine().getStatusCode();
            try{
                entity = resp.getEntity();
                String json = EntityUtils.toString(entity);
                log.info("{} 请求返回结果：{}",url,json);
                return JSON.parseObject(json, ApiResponse.class);
            }catch (Exception e) {
                return ApiResponse.failed(statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ApiResponse.failed(500,"连接失败，请检查设备的网络参数!!!");
        }

    }

    public synchronized static ApiResponse sendDelete(HttpClient client ,String url, String param) {
        HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url); //建立HttpPost对象
        HttpEntity entity = null;
        try {
            //queryBusyStats(client,url);
            if(param!=null){
                StringEntity stringEntity = new StringEntity(param,Charset.forName("UTF-8"));
                httpDelete.setEntity(stringEntity);
            }

            //添加参数
            HttpResponse resp = client.execute(httpDelete);
            int statusCode = resp.getStatusLine().getStatusCode();

            try{
                entity = resp.getEntity();
                String json = EntityUtils.toString(entity);
                log.info("{} 请求返回结果：{}",url,json);
                return JSON.parseObject(json, ApiResponse.class);
            }catch (Exception e) {
                return ApiResponse.failed(statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ApiResponse.failed(500,"连接失败，请检查设备的网络参数!!!");
        }

    }

    /**
     * 查询设备忙碌状态
     * @param client
     * @param url
     */
    private static void queryBusyStats(HttpClient client ,String url){
        while(isBusy(client,url)){
            log.info("设备繁忙，3秒后再发送请求");
            try{
                Thread.sleep(3000);
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try{
            Thread.sleep(2000);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static boolean isBusy(HttpClient client,String url){
        if(url.indexOf(BaseConfig.URL_BASE)>-1){
            url = url.substring(0, url.indexOf(BaseConfig.URL_BASE)) + BaseConfig.URL_BUSY_QUERY;
        }else{
            return false;
        }
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse resp = client.execute(httpGet);
            try{
                HttpEntity entity = resp.getEntity();
                String json = EntityUtils.toString(entity);
                log.info("{} 请求返回结果：{}",url,json);
                JSONObject obj = JSON.parseObject(json).getJSONObject("data");
                return obj.containsKey("operation") && obj.getInteger("operation")!=0;
            }catch (Exception e) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return true;
        }

    }


    private static void testSendPost() {
        HttpClient client = DigestHttpClient.getDigestHttpClient("admin", "admin123", null, null);
        String url = "http://192.168.2.100/" + BaseConfig.URL_FACE_GROUP;

        FaceGroup group = new FaceGroup("德沃");
        ApiResponse resp = DigestHttpUtil.sendPost(client,url,GsonUtils.objToJson(group));
        System.out.println(GsonUtils.objToJson(resp));
    }

    public static void main(String[] args) {
        testSendPost();
    }


}
